/* eslint-disable no-console */
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');

const root = process.cwd();

try {
  const packageJsonStr = fs
    .readFileSync(path.resolve(root, './package.json'))
    .toString();
  const packageJson = JSON.parse(packageJsonStr) || {};
  let [max, mid, min] = (packageJson.version || '').split('.');

  if (Number(min) < 9) {
    min = Number(min) + 1;
  } else if (Number(mid) < 9) {
    mid = Number(mid) + 1;
    min = 0;
  } else {
    max = Number(max) + 1;
    mid = 0;
    min = 0;
  }
  const version = [max, mid, min].join('.');
  packageJson.version = version;
  fs.writeFileSync(
    path.resolve(root, './package.json'),
    JSON.stringify(packageJson)
  );
  execSync('npx prettier -w package.json');
  execSync('git add package.json');
  console.log(`执行version版本号更新操作成功，版本号更新为：${version}`);
} catch (error) {
  console.error('执行version版本号更新操作失败', error);
  process.exit(1);
}
